<?php

require_once 'components/security/base_user_auth.php';
require_once 'components/security/table_based_user_grants_manager.php';
require_once 'components/utils/system_utils.php';
require_once 'components/utils/string_utils.php';

class AdminApplication
{
    /** @var AbstractUserAuthorization */
    private $userAuthorizationStrategy;

    public function SetUserAuthorizationStrategy($userAuthorizationStrategy)
    {
        $this->userAuthorizationStrategy = $userAuthorizationStrategy;
    }

    public function GetUserAuthorizationStrategy()
    {
        return $this->userAuthorizationStrategy;
    }

    public function SetDataSourceRecordPermissionRetrieveStrategy($perms)
    {}

    public function GetCurrentUser()
    {
        return $this->GetUserAuthorizationStrategy()->GetCurrentUser();
    }

    public function HasAdminGrant($userName)
    {
        return $this->userAuthorizationStrategy->HasAdminGrant($userName);
    }
}

$adminApp = new AdminApplication();

/**
 * @return AdminApplication
 */
function GetApplication()
{
    global $adminApp;
    return $adminApp;
}

require_once 'authorization.php';
SetUpUserAuthorization();

class AdminPanelView
{
    private $localizerCaptions = null;

    /** @var TableBasedUserGrantsManager */
    private $tableBasedGrantsManager;

    public function __construct($tableBasedGrantsManager)
    {
        $this->tableBasedGrantsManager = $tableBasedGrantsManager;
    }

    public function GetContentEncoding()
    {
        return 'UTF-8';
    }

    public function GetLocalizerCaptions()
    {
        if (!isset($this->localizerCaptions))
            $this->localizerCaptions = new Captions($this->GetContentEncoding());
        return $this->localizerCaptions;
    }

    public function RenderText($text)
    {
        return ConvertTextToEncoding($text, GetAnsiEncoding(), $this->GetContentEncoding());
    }

    public function GetHeader()
    {
        return '';
    }

    public function Render()
    {
        include_once 'libs/smartylibs/Smarty.class.php';
                
        $smarty = new Smarty();
        $smarty->template_dir = 'components/templates';
        $smarty->assign_by_ref('Page', $this);

        $users = $this->tableBasedGrantsManager->GetAllUsersAsJson();
        $smarty->assign_by_ref('Users', $users);

        $localizerCaptions = $this->GetLocalizerCaptions();
        $smarty->assign_by_ref('Captions', $localizerCaptions);

        /* $roles = $this->tableBasedGrantsManager->GetAllRolesAsJson();
        $smarty->assign_by_ref('Roles', $roles); */

        $headerString = 'Content-Type: text/html';
        if ($this->GetContentEncoding() != null)
            StringUtils::AddStr($headerString, 'charset=' . $this->GetContentEncoding(), ';');
        header($headerString);

        $pageLinks = array();
        $pageInfos = GetPageInfos();
        foreach($pageInfos as $pageInfo)
            array_push(
                $pageLinks,
                array(
                    'Caption' => $this->RenderText($pageInfo['caption']),
                    'Hint' => $this->RenderText($pageInfo['short_caption']),
                    'Link' => $pageInfo['filename'],
                ));

        
        $smarty->assign_by_ref('PageLinks', $pageLinks);
        
        $smarty->display('admin_panel.tpl');
    }

    public function ProcessRequest()
    {
        if (isset($_GET['hname']) )
        {
            header('Content-Type: application/json');

            try
            {
                if ($_GET['hname'] == 'au')
                {
                    $id = $_GET['id'];
                    $userName = $_GET['username'];
                    $password = $_GET['password'];

                    $this->tableBasedGrantsManager->AddUser($id, $userName, $password);

                    echo SystemUtils::ToJSON(
                        array(
                            'status' => 'OK',
                            'result' => array(
                                'id' => $id,
                                'name' => $userName,
                                'password' => '******'
                            )
                        ));
                }
                else if ($_GET['hname'] == 'ru')
                {
                    $user_id = $_GET['user_id'];

                    $this->tableBasedGrantsManager->RemoveUser($user_id);

                    echo SystemUtils::ToJSON(array('status' => 'OK'));
                }
                else if ($_GET['hname'] == 'eu')
                {
                    $user_id = $_GET['user_id'];
                    $userName = $_GET['username'];

                    $newUserName = $this->tableBasedGrantsManager->ChangeUserName($user_id, $userName);

                    echo SystemUtils::ToJSON(array('status' => 'OK', 'result' => array('username' => $newUserName)));
                }
                else if ($_GET['hname'] == 'cup')
                {
                    $user_id = $_GET['user_id'];
                    $password = $_GET['password'];

                    $this->tableBasedGrantsManager->ChangeUserPassword($user_id, $password);

                    echo SystemUtils::ToJSON(array('status' => 'OK'));
                }
                else if ($_GET['hname'] == 'gug')
                {
                    $user_id = $_GET['user_id'];

                    echo $this->tableBasedGrantsManager->GetUserGrantsAsJson($user_id);
                }
                else if ($_GET['hname'] == 'aug')
                {
                    $user_id = $_GET['user_id'];
                    $page_name = $_GET['page_name'];
                    $grant = $_GET['grant'];

                    $this->tableBasedGrantsManager->AddUserGrant($user_id, $page_name, $grant);
                    echo SystemUtils::ToJSON(array('status' => 'OK'));
                }
                else if ($_GET['hname'] == 'rug')
                {
                    $user_id = $_GET['user_id'];
                    $page_name = $_GET['page_name'];
                    $grant = $_GET['grant'];

                    $this->tableBasedGrantsManager->RemoveUserGrant($user_id, $page_name, $grant);
                    echo SystemUtils::ToJSON(array('status' => 'OK'));
                }
            }
            catch (Exception $e)
            {
                echo SystemUtils::ToJSON(
                    array(
                        'status' =>'error',
                        'result' => $e->getMessage()));
            }
            return true;
        }
        return false;
    }
}

$tableBasedGrants = CreateTableBasedGrantsManager();

$view = new AdminPanelView($tableBasedGrants);

if (!GetApplication()->HasAdminGrant(GetApplication()->GetCurrentUser()))
{
    include_once 'components/error_utils.php';
    RaiseSecurityError($view, 'You do not have permission to access this page.');
}

if (!$view->ProcessRequest())
    $view->Render();